package com.grandt.model.database.manager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.grandt.model.configuration.ConfigurationBean;
import com.grandt.model.exceptions.BuscarDatosException;
import com.grandt.model.exceptions.InsertDataException;

public abstract class ManagerDataBase {
	protected Connection						connection;
	public ManagerDataBase(ConfigurationBean configuration) {
		try {
			setConnection(configuration);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void setConnection(ConfigurationBean configuration) throws ClassNotFoundException, SQLException {		        	
		Class.forName(configuration.getDriver());
        connection = DriverManager.getConnection(configuration.getUrl(),configuration.getUser(),configuration.getPassword());
	}
	public Connection getConnection() {
		return connection;
	}
	public void insert(Object object) throws InsertDataException{
		try {
			String query = getStrInsert();
			PreparedStatement prst;
			prst = connection.prepareStatement(query);
			insertParameters(prst,object);
			prst.execute();
			prst.getConnection().commit();
			prst.close();
		} catch (SQLException e) {
			throw new InsertDataException(e);
		}
	}
	public void commit() throws SQLException{
		connection.commit();
	}
	public void rollback(){
		try {
			connection.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public List<Object> query(Object o) throws BuscarDatosException {
		try {
			List<Object> list=null;
			String query = getStrQuery();
			PreparedStatement prst;
			prst = connection.prepareStatement(query);
			queryParameters(prst,o);
			ResultSet result = prst.executeQuery();
			list = getResult(result);
			prst.close();
			return list;
		} catch (SQLException e) {
			throw new BuscarDatosException(e);
		}
	}
	protected abstract void queryParameters(PreparedStatement prst, Object o);
	protected abstract String getStrQuery();
	protected abstract List<Object> getResult(ResultSet result) ;
	protected abstract void insertParameters(PreparedStatement prst,Object o)throws SQLException ;
	protected abstract String getStrInsert();
}
